<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\TagRequest;
use App\Http\Requests\TagUpdateRequest;
use App\Http\Responses\Response;
use App\Models\Tag;
use Illuminate\Http\JsonResponse;

class TagController extends Controller
{
    public function list(): JsonResponse
    {
        $tags = Tag::withCount("posts")->get();
        return Response::resource_success($tags);
    }

    public function delete($id): JsonResponse
    {
        $tag = Tag::find($id);
        if(!$tag){
            return Response::not_found();
        }
        $tag->delete();
        return Response::delete_success($tag);
    }

    public function save(TagRequest $request): JsonResponse
    {
        $tag = Tag::create($request->validated());
        return Response::insert_success($tag);
    }

    public function update(TagRequest $request, $id): JsonResponse
    {
        $tag = Tag::find($id);
        if(!$tag){
            return Response::not_found();
        }
        $tag->update($request->validated());
        return Response::update_success($tag);
    }
}
